﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.iss.inventory.Entity;
using com.iss.inventory.Controllers;
using com.iss.inventory.BusinessLogic;
using com.iss.inventory.CustomModels;


namespace Staionery_Inventory.Presentation.StationeryRetrieval
{
    public partial class StationeryRetrievalForm : System.Web.UI.Page
    {
        StationeryRetrievalController srfControl = new StationeryRetrievalController();
        List<SRFDetail> srfDetailsList = new List<SRFDetail>();
        SearchController searchControl = new SearchController();
        customSRFDetailsModel customSRFModel; InvManagementEntities inv;
       
        protected void Page_Load(object sender, EventArgs e)
        {
          //allow only logged in users
          if (Session["empID"] == null)
            {
                Response.Redirect("~/Presentation/login.aspx");
            }

            Label lbl = this.Master.FindControl("lblLogInName") as Label;
            if (lbl != null)
            {
                lbl.Text = Session["UserName"].ToString();
            }


            string prevURL;
            if (!IsPostBack) //first time loading page
            {
                customSRFModel = new customSRFDetailsModel();

                //get trace from which page it entered this page
                if (Request.UrlReferrer != null)
                {
                    ViewState["prevToSRFpage"] = Request.UrlReferrer;
                    prevURL = ViewState["prevToSRFpage"].ToString();
                }
                else
                {
                    prevURL = "abc";
                }
                //for creating new SRF only
                if ((!prevURL.Contains("SRFList.aspx"))||((Request.QueryString["srfID"] == null)&&prevURL.Contains("SRFList.aspx"))) //need to freeze srf form once it is create for a week, cannot create more than one for a week 
                {
                    // check if any SRF is created and if last form not disbursed redirect
                    inv = new InvManagementEntities();
                    string srfstatus = (from s in inv.SRFs orderby s.SRFID descending select s).First().StatusforForm;
                    if (srfstatus == "Created")
                    {
                        System.Windows.Forms.MessageBox.Show("Please Disburse previous SRF before creating new one ", "Can not create SRF");
                        Response.Redirect("~/Presentation/StationeryRetrieval/SRFList.aspx");
                    }

                    //for creating new SRF only when no previous undisbursed SRF present
                    if (srfControl.getIncompleteRequestsforSRF() != null)
                    {
                        customSRFModel = srfControl.getIncompleteRequestsforSRF();
                        srfDetailsList = customSRFModel.srfDetailsList;
                        btnDisburseSRF.Enabled = false;
                        btnGenerateSRF.Enabled = true;
                    }
                    else // if no requests, then show nothing
                    {
                        lblFeedback.Text = "No Pending Requests";
                        btnDisburseSRF.Enabled = false;
                        btnGenerateSRF.Enabled = false;
                    }
                }
                else //for existing created SRF
                {
                    int srfID = 0; //need  to assign a default value
                    if (lblSrfIdValue.Text != "")
                    {
                        srfID = Convert.ToInt32(lblSrfIdValue.Text);
                    }
                    if (Request.QueryString["srfID"] != null)
                    {
                        srfID = Convert.ToInt32(Request.QueryString["srfID"].ToString());
                    }

                    //get SRF details from database
                    SRF srf = srfControl.getSRF(srfID);
                    srfDetailsList.Clear(); //

                    foreach (SRFDetail srfd in srf.SRFDetails)
                    {
                        srfDetailsList.Add(srfd);
                    }

                    btnGenerateSRF.Enabled = false;
                    btnDisburseSRF.Enabled = true;
                    lblSrfIdValue.Text = srf.SRFID.ToString();
                    if (srf.StatusforForm.Contains("Disbursed"))
                        btnDisburseSRF.Enabled = false;
                }

                //get SRF Details for display in datagrid, for both pending and created SRF 
                var custom = from s in srfDetailsList
                             select new { ItemDescription = s.StationeryItem.Description, StockAvailable = s.StationeryItem.QtyLeft, DepartmentName = s.Department.DeptName, NeededQty = s.QtyRequested, ActualQty = s.QtyRetrieved };
                gvSrfList.DataSource = custom.ToList<object>();
                gvSrfList.DataBind();

                //assign into customSRFModel to store it into viewstate to retain during postback
                customSRFModel.srfDetailsList = srfDetailsList; //added new
                ViewState["srfDetailsList"] = customSRFModel;

                //display status of SRF in the label for feedback
                if(srfDetailsList.Count != 0)
                if (srfDetailsList[0].SRF != null)
                    lblFeedback.Text = srfDetailsList[0].SRF.StatusforForm;
                else
                    lblFeedback.Text = "new";
            }
            else // on postback, get viewstate values to rebind to grid
            {
                customSRFModel = ViewState["srfDetailsList"] as customSRFDetailsModel;
                srfDetailsList = customSRFModel.srfDetailsList;
            }
        }

        protected void gvSrfList_DataBound(object sender, EventArgs e)
        {
            for (int rowIndex = gvSrfList.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            {
                GridViewRow gvRow = gvSrfList.Rows[rowIndex];
                GridViewRow gvPreviousRow = gvSrfList.Rows[rowIndex + 1];
                for (int cellCount = 0; cellCount < 1; cellCount++)
                {
                    if (gvRow.Cells[cellCount].Text == gvPreviousRow.Cells[cellCount].Text)
                    {
                        if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
                        {
                            gvRow.Cells[cellCount].RowSpan = 2;
                          gvRow.Cells[cellCount+1].RowSpan = 2;
                        }
                        else
                        {
                            gvRow.Cells[cellCount].RowSpan = gvPreviousRow.Cells[cellCount].RowSpan + 1;
                            gvRow.Cells[cellCount+1].RowSpan = gvPreviousRow.Cells[cellCount+1].RowSpan + 1;
                        }
                        gvPreviousRow.Cells[cellCount].Visible = false;
                       gvPreviousRow.Cells[cellCount+1].Visible = false;
                    }
                }
            }
            
            if(srfDetailsList.Count!=0)
            if(srfDetailsList[0].SRF != null)
            if(srfDetailsList[0].SRF.StatusforForm.Contains("Disbursed"))
            foreach (GridViewRow r in gvSrfList.Rows)
            {
                TextBox txt = r.FindControl("actualQty") as TextBox;
                txt.Enabled = false;
            }

        }

        protected void btnGenerateSRF_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow r in gvSrfList.Rows)
            {
                string itemName = r.Cells[0].Text;
                string deptName = r.Cells[2].Text;
                TextBox txt = r.FindControl("actualQty") as TextBox;
                string actualQty = txt.Text;
                srfDetailsList[r.RowIndex].QtyRetrieved = Convert.ToInt32(actualQty);
            }
            
            int empId = Convert.ToInt32(Session["empID"].ToString());

            int srfID = srfControl.saveSrfDetails(customSRFModel, empId);

            //int srfID = srfControl.saveSrfDetails(srfDetailsList,empId);

            customSRFModel.srfDetailsList = srfControl.getSRFDetails_bySRFID(srfID);

            lblSrfIdValue.Text = srfID.ToString();
            lblFeedback.Text = "Saved SRF";
            btnGenerateSRF.Enabled = false;
            btnDisburseSRF.Enabled = true;
            ViewState["srfDetailsList"] = customSRFModel;
        }

        protected void btnDisburseSRF_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow r in gvSrfList.Rows)
            {
                string itemName = r.Cells[0].Text;
                string deptName = r.Cells[2].Text;
                TextBox txt = r.FindControl("actualQty") as TextBox;
                string actualQty = txt.Text;
                customSRFModel.srfDetailsList[r.RowIndex].QtyRetrieved = Convert.ToInt32(actualQty);
            }
            if (srfControl.generateDisbursementList(customSRFModel.srfDetailsList))
            {
                lblFeedback.Text = "Disbursed";
                btnDisburseSRF.Enabled = false;
                btnGenerateSRF.Enabled = false;
            }
            else
            {
                lblFeedback.Text = "Insufficient Quantity. Enter Sufficient Amount.";
                btnDisburseSRF.Enabled = true;
                btnGenerateSRF.Enabled = false;
            }
            ViewState["srfDetailsList"] = customSRFModel;
            //Response.Redirect("~/Presentation/StationeryRetrieval/StationeryRetrievalForm.aspx?srfID=" + srfDetailsList[0].SRFID);
        }

        protected void actualQty_TextChanged(object sender, EventArgs e)
        {
          customSRFDetailsModel csrcurrent=ViewState["srfDetailsList"] as customSRFDetailsModel;
            TextBox txt = sender as TextBox;
            GridViewRow gr = txt.NamingContainer as GridViewRow;
            string qty =txt.Text;
            csrcurrent.srfDetailsList[gr.RowIndex].QtyRetrieved = Convert.ToInt32(qty);
            ViewState["srfDetailsList"] = csrcurrent;
        }
    }
}